package com.leisurexi.gedis.client.util;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

/**
 * 同步等待响应结果工具类
 *
 * @author: leisurexi
 * @date: 2020-12-09 16:42
 */
@Slf4j
public class SynchronizeWaitUtils {

    private static final int DEFAULT_TIMEOUT = 30;

    private SynchronizeWaitUtils() {
    }

    private static final ConcurrentHashMap<String, SynchronousQueue<Object>> map = new ConcurrentHashMap();

    public static Object getResult(String key) {
        return getResult(key, DEFAULT_TIMEOUT, TimeUnit.SECONDS);
    }

    public static Object getResult(String key, long timeout, TimeUnit timeUnit) {
        SynchronousQueue<Object> queue = map.compute(key, (s, obj) -> new SynchronousQueue<>());
        if (queue != null) {
            try {
                Object result = queue.poll(timeout, timeUnit);
                return result;
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            } finally {
                map.remove(key);
            }
        }
        return null;
    }

    public static void putResult(String key, Object result) {
        SynchronousQueue<Object> queue = map.get(key);
        if (queue != null) {
            try {
                queue.put(result);
            } catch (InterruptedException e) {
                // ignore
            }
        }
    }

}
